package com.leil.movies.project.config;

import com.leil.movies.project.rest.handler.DouBanApiErrorHandler;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@Configuration
public class RestConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory, DouBanApiErrorHandler douBanApiErrorHandler) {
        RestTemplate restTemplate = new RestTemplate(factory);
        // 自定义异常处理
        restTemplate.setErrorHandler(douBanApiErrorHandler);
        // 支持中文编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setReadTimeout(5000);
        clientHttpRequestFactory.setConnectTimeout(5000);
        return clientHttpRequestFactory;
    }

    @Bean
    public DouBanApiErrorHandler douBanApiErrorHandler() {
        return new DouBanApiErrorHandler();
    }


}
